// 阅读器页面
import 'dart:math';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:ibook/appconfig/appconfig.dart';
import '../db/booksManager.dart';
import 'dart:convert';

class Reader extends StatefulWidget {
  // final List<Map<String, Object?>> content;
  final booksManager db;
  final String contengTableName;
  final List<Map<String, Object?>> firstChapter;
  final String bookName;
  final double width;
  final double height;
  Reader({Key? key, required this.firstChapter, required this.bookName, required this.db, required this.contengTableName, required this.width, required this.height}) : super(key: key);
  @override
  _ReaderPageState createState() => _ReaderPageState();
}

class _ReaderPageState extends State<Reader> {
  List<Map<String, Object?>> chapters = []; //章节内容
  bool _isLoadingNextOptions = true; //用于控制底部栏的显示
  bool _isLoadingNextSettings = true; //用于控制设置弹窗的显示
  bool _isLoadingNextMenu = false; //用于控制菜单的显示
  double fontSizevalue = 24; //用于控制字体大小
  Map<String, Object?> firstChapter = {};
  List<String> chapterMenu = []; //章节菜单
  late PageController _pageController;
  int _initialPage = 0;
  int currentPage = 0; //当前页
  int currentChapterID = 0; //当前章节ID
  Map<String, dynamic> bookmark = {}; //书签
  int _chapterNum = 0;
  List<String> pages = [];
  List<String> newPages = [];
  List<String> oldPages = [];
  int pageStringLength = 0;
  String chapterName = "";
  // 添加类成员变量
  double cachedWidth = 0;
  double cachedHeight = 0;
  // 背景颜色列表
  double _lastOffset = 0;
  List<String> reader_background = ["assets/images/ReadBG_1.png", "assets/images/backIMG.jpg", "assets/images/ReadBG_2.jpg", "assets/images/ReadBG_3.jpg", "assets/images/ReadBG_4.jpg"];
  String bgColor = "assets/images/ReadBG_3.jpg";
  // 添加目录滚动控制器
  final ScrollController _chapterScrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final dimensions = AppConfig.dimensions; // 提前获取基础数据
      firstChapter = widget.firstChapter[0];
      // print("第一章内容: ${firstChapter}");
      currentChapterID = firstChapter['id'] as int;
      final book = await widget.db.getBookInfo(widget.bookName);
      // print("ce: ${book[0]['catalogue']}");
      // chapterMenu = jsonDecode(cese[0]['catalogue']);
      List<dynamic> dynamicList = jsonDecode(book[0]['catalogue'].toString());
      chapterMenu = dynamicList.cast<String>();
      // print("查询目录：${se[100]}");
      // 在调用分页前计算参数
      final Map<String, dynamic> params = {
        'content': firstChapter['chapter'].toString(),
        'fontSize': fontSizevalue,
        'pageWidth': dimensions['width']!,
        'pageHeight': dimensions['height']!,
        'lineHeightMultiple': 1.5 // 行高倍数
      };

// 计算近似字符数
      final approxParams = _calculateApproxParams(params);
      final combinedParams = {...params, ...approxParams};

      // 在PaginationWorker中使用
      var pages = await PaginationWorker.paginate(combinedParams);
      setState(() {
        // chapters=widget.ge;
        this.pages = pages;
      });
      // print("pages: ${firstChapter}");
      _pageController = PageController(
        initialPage: _initialPage,
      );
      // 加状态锁
      bool _isLoadingNext = false; // 用于判断是否加载下一章节内容
      bool _isLoadingPrev = false; // 用于判断是否加载上一章节内容
      ScrollDirection _lastScrollDirection = ScrollDirection.idle;

      //  监听页面滚动
      _pageController.addListener(() async {
        //防止频繁触发
        if (_isLoadingNext || _isLoadingPrev) return;
        // **********************************************************************************
        final currentOffset = _pageController.position.pixels;
        final maxScroll = _pageController.position.maxScrollExtent;
        final minScroll = _pageController.position.minScrollExtent;
        // 更新底部栏的显示
        setState(() {
          _isLoadingNextOptions = true;
        });
        // 更新滚动方向
        _lastScrollDirection = currentOffset > _lastOffset ? ScrollDirection.forward : ScrollDirection.reverse;
        _lastOffset = currentOffset;
        _lastOffset = currentOffset;
        //*************************************************************************************** */
        // 加载下一章节的内容
        //*************************************************************************************** */
        if (currentOffset > maxScroll + 1 && _lastScrollDirection == ScrollDirection.forward) {
          // 添加章节越界保护
          _isLoadingNext = true;
          if (_chapterNum + 1 >= chapterMenu.length) {
            print("已到达最后一章");
            _isLoadingNext = false;
            return;
          }

          // final nextChapterContent = chapters[_chapterNum += 1]['chapter']?.toString() ?? '';
          _chapterNum += 1;
          final chapterCT = await widget.db.getBookContentInfo(widget.contengTableName, currentChapterID + 1, currentChapterID + 2);
          final nextChapterContent = chapterCT[0]['chapter'].toString() ?? '';

          currentChapterID++;

          newPages = await PaginationWorker.paginate({
            'content': nextChapterContent,
            'pageWidth': dimensions['width']!,
            'pageHeight': dimensions['height']!,
            'fontSize': fontSizevalue,
            'charsPerPage': combinedParams['charsPerPage'], // 确保传递计算参数
            'maxAdjustment': combinedParams['maxAdjustment']
          });

          if (mounted) {
            setState(() {
              // 如果到最后一页了，就清空pages，重新加载数据
              pages.clear();
              pages.addAll(newPages);
              // _pageController.jumpToPage(0);
              _pageController.animateToPage(
                0,
                duration: Duration(milliseconds: 1), // 动画时长
                curve: Curves.easeInOut, // 动画曲线
              );
              // chapterName = chapters[_chapterNum - 1]['title'].toString();
              chapterName = chapterMenu[_chapterNum - 1];
            });
          }
          // 延迟解锁确保布局稳定
          Future.delayed(Duration(milliseconds: 100), () => _isLoadingNext = false);
        }
        //*************************************************************************************** */
        // 加载上一章节的内容
        //*************************************************************************************** */
        else if (currentOffset < minScroll - 1 && _lastScrollDirection == ScrollDirection.reverse) {
          _isLoadingPrev = true;
          if (_chapterNum - 1 >= 0) {
            _chapterNum--;
            final chapterCT = await widget.db.getBookContentInfo(widget.contengTableName, currentChapterID - 1, currentChapterID);
            final nextChapterContent = chapterCT[0]['chapter'].toString() ?? '';
            currentChapterID--;
            oldPages = await PaginationWorker.paginate({
              'content': nextChapterContent,
              'pageWidth': dimensions['width']!,
              'pageHeight': dimensions['height']!,
              'fontSize': fontSizevalue,
              'charsPerPage': combinedParams['charsPerPage'], // 确保传递计算参数
              'maxAdjustment': combinedParams['maxAdjustment']
            });
          } else {
            print("已到达第一章");
            _isLoadingPrev = false;
            return;
          }
          setState(() {
            pages.clear();
            pages.addAll(oldPages);
            _pageController.animateToPage(
              oldPages.length - 1,
              duration: Duration(milliseconds: 1), // 动画时长
              curve: Curves.easeOut, // 动画曲线
            );
            if (_chapterNum - 1 >= 0) {
              chapterName = chapterMenu[_chapterNum - 1];
            } else
              chapterName = "";
          });
          Future.delayed(Duration(milliseconds: 100), () => _isLoadingPrev = false);
        }
      });
    });
  }

  Map<String, dynamic> _calculateApproxParams(Map<String, dynamic> params) {
    // 基于"中"字符计算单个字符宽度
    final testText = '中' * 10;
    final lineHeightMultiple = (params['lineHeightMultiple'] as num?)?.toDouble() ?? 1.5;
    final textPainter = TextPainter(
      text: TextSpan(
        text: testText,
        style: TextStyle(
          fontSize: params['fontSize'],
          height: lineHeightMultiple,
        ),
      ),
      textDirection: TextDirection.ltr,
    );

    textPainter.layout(maxWidth: params['pageWidth']);

    final charWidth = textPainter.width / 10;
    final lineCharCount = (params['pageWidth'] / charWidth).floor();

    final lineHeight = textPainter.height / 10; // 单行高度
    final linesPerPage = (params['pageHeight'] / lineHeight).floor();

    textPainter.dispose();

    return {
      'charsPerPage': lineCharCount * linesPerPage,
      'maxAdjustment': lineCharCount // 每行字符数作为最大调整量
    };
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    cachedWidth = AppConfig.pageWidth; // 直接使用全局配置
    cachedHeight = AppConfig.pageHeight;
  }

  Future<void> _animateToFirstPageOfNewData(int targetPageIndex) async {
    await _pageController.animateToPage(
      targetPageIndex,
      duration: Duration(milliseconds: 100), // 自定义动画时长
      curve: Curves.easeOutBack, // 自定义动画曲线
    );
  }

  // 销毁阶段
  @override
  void dispose() {
    _pageController.dispose();
    bookmark = {'chapterID': currentChapterID, 'page': currentPage};
    // widget.db.updateBookInfo(widget.content[0]["id"].toString(), "bookmark", bookmark.toString());
    // print("销毁:book:$book")
    _chapterScrollController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 屏幕宽度
    final size = AppConfig.dimensions;
    final widthOfscreen = size['width']!;
    final heightOfscreen = size['height']!;

    // 底部栏弹窗
    Widget readerOptions() {
      return AnimatedPositioned(
          duration: Duration(milliseconds: 400),
          curve: Curves.elasticInOut,
          bottom: _isLoadingNextOptions ? -100 : 24,
          left: 0,
          right: 0,
          child: Stack(
            children: [
              Center(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(20), // 圆角裁剪
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 1, sigmaY: 1), // 模糊参数
                    child: AnimatedContainer(
                      duration: Duration(milliseconds: 400),
                      width: _isLoadingNextOptions ? widthOfscreen * .7 : widthOfscreen,
                      height: _isLoadingNextOptions ? 50 : 75,
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.1), // 半透明底色
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(color: Colors.white.withOpacity(.5), width: 1, style: BorderStyle.solid),
                        boxShadow: [
                          BoxShadow(
                            color: Color.fromARGB(255, 244, 248, 248).withOpacity(0.3),
                            blurRadius: 24,
                            spreadRadius: -1,
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              Center(
                  child: ClipRRect(
                // 使边框变成圆角
                borderRadius: BorderRadius.circular(16),
                // 为组件添加动画
                child: AnimatedContainer(
                    duration: Duration(milliseconds: 400),
                    curve: Curves.easeInOut,
                    width: _isLoadingNextOptions ? widthOfscreen * .7 : widthOfscreen,
                    height: _isLoadingNextOptions ? 50 : 75,
                    padding: EdgeInsets.all(12),
                    // color: Color.fromARGB(255, 113, 219, 210),
                    child: AnimatedOpacity(
                      duration: Duration(milliseconds: 400),
                      opacity: _isLoadingNextOptions ? 0.5 : 0.6,
                      curve: Curves.bounceInOut,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          FloatingActionButton(
                            heroTag: "menu",
                            onPressed: () {
                              setState(() {
                                _isLoadingNextMenu = !_isLoadingNextMenu;
                              });
                              if (!_isLoadingNextMenu) {
                                WidgetsBinding.instance.addPostFrameCallback((_) {
                                  _scrollToCurrentChapter();
                                });
                              }
                            },
                            backgroundColor: Colors.white.withOpacity(.7),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.menu),
                            tooltip: "目录",
                          ),
                          FloatingActionButton(
                            heroTag: "font",
                            onPressed: () {},
                            backgroundColor: Colors.white.withOpacity(.7),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.font_download),
                            tooltip: "字体",
                          ),
                          FloatingActionButton(
                            heroTag: "settings",
                            onPressed: () {
                              setState(() {
                                _isLoadingNextSettings = !_isLoadingNextSettings;
                              });
                            },
                            backgroundColor: Colors.white.withOpacity(.7),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.settings),
                            tooltip: "设置",
                          ),
                          FloatingActionButton(
                            heroTag: "nightMode",
                            onPressed: () {},
                            backgroundColor: Colors.white.withOpacity(.7),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.brightness_3),
                            tooltip: "夜间模式",
                          ),
                        ],
                      ),
                    )),
              ))
            ],
          ));
    }

    // 设置弹窗
    Widget settings() {
      return AnimatedPositioned(
          duration: Duration(milliseconds: 300),
          curve: Curves.fastOutSlowIn,
          bottom: _isLoadingNextSettings ? -300 : 120,
          left: 0,
          right: 0,
          child: Center(
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: AnimatedContainer(
                      duration: Duration(milliseconds: 100),
                      width: widthOfscreen,
                      height: 300,
                      color: Colors.white.withOpacity(.9),
                      child: Column(
                        children: [
                          // 背景颜色设置
                          Container(
                            width: widthOfscreen * .8,
                            margin: EdgeInsets.all(12),
                            height: 50,
                            child: ListView(
                              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              reverse: true,
                              scrollDirection: Axis.horizontal,
                              shrinkWrap: true,
                              children: [
                                ...reader_background.map((bg) {
                                  return GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          bgColor = bg;
                                        });
                                      },
                                      child: Container(
                                        margin: EdgeInsets.only(right: 10),
                                        decoration: BoxDecoration(
                                            image: DecorationImage(
                                              image: AssetImage(bg), // 你的图片路径
                                              fit: BoxFit.cover, // 填充方式
                                              colorFilter: ColorFilter.mode(
                                                Colors.white.withOpacity(0.1), // 添加透明度确保文字可读
                                                BlendMode.dstOver,
                                              ),
                                            ),
                                            gradient: LinearGradient(
                                              colors: [
                                                Colors.white.withOpacity(0.4),
                                                Colors.white.withOpacity(0.1),
                                              ],
                                              begin: const Alignment(-1, -1),
                                              end: const Alignment(0.3, 0.5),
                                            ),
                                            borderRadius: BorderRadius.circular(5),
                                            boxShadow: [
                                              BoxShadow(
                                                color: const Color(0x000000).withOpacity(0.1),
                                                offset: const Offset(0, 1),
                                                blurRadius: 24,
                                                spreadRadius: -1,
                                              )
                                            ],
                                            border: Border.all(
                                              color: Colors.black,
                                              width: 1,
                                            )),
                                        child: ClipRRect(
                                          borderRadius: BorderRadius.circular(5),
                                          child: Container(
                                            width: 50,
                                            height: 50,
                                          ),
                                        ),
                                      ));
                                }).toList()
                              ],
                            ),
                          ),

                          // 字体大小设置
                          Container(
                            width: widthOfscreen * .8,
                            margin: EdgeInsets.all(12),
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5),
                              border: Border.all(
                                color: Colors.grey,
                                width: 1,
                              ),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                    width: widthOfscreen * .1,
                                    height: widthOfscreen * .1,
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (fontSizevalue >= 13) {
                                            fontSizevalue -= 1;
                                          }
                                        });
                                      },
                                      child: Icon(Icons.remove),
                                    )),
                                Container(
                                    width: widthOfscreen * .5,
                                    height: widthOfscreen * .1,
                                    child: Material(
                                      child: Slider(value: fontSizevalue, min: 12.0, max: 32.0, activeColor: Colors.black, inactiveColor: Colors.blue, onChanged: _fontSizeChanged),
                                    )),
                                Container(
                                    width: widthOfscreen * .1,
                                    height: widthOfscreen * .1,
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (fontSizevalue <= 31) {
                                            fontSizevalue += 1;
                                          }
                                        });
                                      },
                                      child: Icon(Icons.add),
                                    ))
                              ],
                            ),
                          ),

                          // 行距设置
                          Container(
                              width: widthOfscreen * .8,
                              margin: EdgeInsets.all(12),
                              padding: EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(5),
                                border: Border.all(
                                  color: Colors.grey,
                                  width: 1,
                                ),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [Icon(Icons.density_large), Icon(Icons.density_medium), Icon(Icons.density_small)],
                              ))
                        ],
                      )))));
    }

    //目录弹窗
    Widget Menu() {
      return AnimatedPositioned(
          top: 0,
          left: _isLoadingNextMenu ? 0 : -(widthOfscreen / .8),
          duration: Duration(microseconds: 1000),
          child: Stack(
            children: [
              Container(
                  width: widthOfscreen / .8,
                  height: heightOfscreen / .8,
                  padding: EdgeInsets.only(left: 12, top: 70),
                  color: Color(0xffBED9DD),
                  child: ListView(controller: _chapterScrollController, children: [
                    // 章节列表
                    ...chapterMenu.asMap().entries.map((entry) {
                      final chapterIndex = entry.key; // 索引
                      final chapterName = entry.value; // 章节名称
                      return Center(
                          child: Container(
                        height: 40,
                        alignment: Alignment.centerLeft,
                        decoration: BoxDecoration(
                          border: Border(bottom: BorderSide(color: Colors.white, width: .1)),
                        ),
                        child: GestureDetector(
                            onTap: () {
                              print(chapterIndex);
                              // 跳转到指定章节
                              _navigateToChapter(chapterIndex + 1);
                            },
                            child: Text(
                              chapterName,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                                color: chapterMenu[currentChapterID - 1 >= 0 ? currentChapterID - 1 : currentChapterID] == chapterName ? Colors.blue[300] : Colors.black,
                                decoration: TextDecoration.none,
                              ),
                            )),
                      ));
                    }).toList()
                  ])),
              Positioned(
                  top: 0,
                  left: 0,
                  child: Container(
                    alignment: Alignment.center,
                    width: widthOfscreen / .8,
                    height: 100,
                    color: Color(0xffAECFD0),
                    padding: EdgeInsets.only(top: 40),
                    child: Text('目录',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.w900,
                          color: Colors.black,
                          decoration: TextDecoration.none,
                        )),
                  )),
            ],
          ));
    }

    // 返回阅读器组件
    return Stack(children: [
      // 背景
      Positioned(
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(bgColor), // 你的图片路径
              fit: BoxFit.cover, // 填充方式
              colorFilter: ColorFilter.mode(
                Colors.white.withOpacity(0.1), // 添加透明度确保文字可读
                BlendMode.dstOver,
              ),
            ),
          ),
          // color: bgColor,
          width: widthOfscreen,
          height: heightOfscreen,
        ),
      ),

      // 内容展示 如果内容不为空就渲染
      if (pages.isNotEmpty)
        Container(
            margin: EdgeInsets.only(left: 24, top: 70, right: 24, bottom: 24),
            child: PageView.builder(
                controller: _pageController,
                itemCount: pages.length,
                physics: const BouncingScrollPhysics(),
                onPageChanged: (index) {
                  setState(() {
                    currentPage = index;
                  });
                },
                itemBuilder: (context, index) {
                  // 使用textpainter绘制文本内容s
                  return LayoutBuilder(builder: (context, constraints) {
                    return CustomPaint(
                      painter: contentPainter(pages: [pages[index]], fontSizevalue: fontSizevalue),
                      size: Size(constraints.maxWidth, constraints.maxHeight),
                    );
                  });
                })),
      // 章节名
      Positioned(
        top: 32,
        left: 24,
        right: 0,
        child: Container(
          width: widthOfscreen,
          height: 50,
          child: Text(
            chapterName,
            style: TextStyle(
              color: const Color.fromARGB(255, 20, 20, 20),
              fontSize: 16,
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ),
      // 页数
      Positioned(
        left: widget.width * 0.05,
        bottom: 10,
        child: Container(
          width: widthOfscreen,
          height: 50,
          child: Text(
            "${(currentPage + 1).toString()}/${pages.length.toString()}页",
            style: TextStyle(
              color: const Color.fromARGB(255, 20, 20, 20),
              fontSize: 12,
              fontWeight: FontWeight.normal,
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ),

      // 按钮
      Center(
          child: Opacity(
        opacity: 0,
        // 为子组件添加点击事件
        child: GestureDetector(
          child: Container(
            width: 100,
            height: 200,
            color: Color.fromARGB(255, 212, 211, 211),
          ),
          onTap: () {
            setState(() {
              _isLoadingNextOptions = !_isLoadingNextOptions;
              _isLoadingNextSettings = true;
            });
          },
        ),
      )),

      // 设置弹窗
      settings(),
      //菜单弹窗
      Menu(),
      // 页面属性设置
      readerOptions(),
    ]);
  }

  void _fontSizeChanged(value) {
    setState(() {
      fontSizevalue = value;
    });
  }

  //跳转到目的章节
  void _navigateToChapter(int targetChapterId) async {
    // 关闭菜单
    setState(() {
      _isLoadingNextMenu = false;
    });

    // 如果目标章节就是当前章节，则无需操作
    if (targetChapterId == currentChapterID) {
      return;
    }

    final dimensions = AppConfig.dimensions;
    final Map<String, dynamic> params = {'fontSize': fontSizevalue, 'pageWidth': dimensions['width']!, 'pageHeight': dimensions['height']!, 'lineHeightMultiple': 1.5};

    // 计算近似字符数
    final approxParams = _calculateApproxParams(params);
    final combinedParams = {...params, ...approxParams};

    // 获取目标章节内容
    final chapterCT = await widget.db.getBookContentInfo(widget.contengTableName, targetChapterId, targetChapterId + 1);

    if (chapterCT.isEmpty) return;

    final targetChapterContent = chapterCT[0]['chapter'].toString();
    print("屏幕尺寸: ${dimensions['width']} x ${dimensions['height']}");

    // 分页处理
    final targetPages = await PaginationWorker.paginate({
      'content': targetChapterContent,
      'pageWidth': dimensions['width']!,
      'pageHeight': dimensions['height']!,
      'fontSize': fontSizevalue,
      'charsPerPage': combinedParams['charsPerPage'],
      'maxAdjustment': combinedParams['maxAdjustment']
    });

    // 更新状态
    setState(() {
      // 更新当前章节ID和索引
      currentChapterID = targetChapterId;
      _chapterNum = targetChapterId - 1;

      // 清空并更新页面内容
      pages.clear();
      pages.addAll(targetPages);

      // 更新章节名称
      if (_chapterNum >= 0 && _chapterNum < chapterMenu.length) {
        chapterName = chapterMenu[_chapterNum];
      } else {
        chapterName = "";
      }

      // 跳转到章节的第一页
      _pageController.jumpToPage(0);
    });
  }

  // 滚动到当前章节位置
  void _scrollToCurrentChapter() {
    if (_chapterScrollController.hasClients) {
      final itemHeight = 40.0;
      final currentChapterIndex = currentChapterID - 1;

      // 计算将当前章节置于中间位置所需的偏移量
      final targetPosition = currentChapterIndex * itemHeight - (_chapterScrollController.position.viewportDimension / 2) + (itemHeight / 2);

      // 执行滚动动画
      _chapterScrollController.animateTo(
        targetPosition.clamp(0.0, _chapterScrollController.position.maxScrollExtent),
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }
}

//********************************************************************************* */
// 后台处理分页操作
class PaginationWorker {
  // 移除 isolate 方式，直接在主线程进行精确分页
  static Future<List<String>> paginate(Map<String, dynamic> params) async {
    // 直接在主线程进行分页，因为需要使用 TextPainter
    return _paginateOnMainThread(params);
  }

  // 在主线程进行精确分页
  static List<String> _paginateOnMainThread(Map<String, dynamic> params) {
    final content = params['content'] as String;
    final pageWidth = params['pageWidth'] as double;
    final pageHeight = params['pageHeight'] as double;
    final fontSize = params['fontSize'] as double;
    final lineHeightMultiple = (params['lineHeightMultiple'] as num?)?.toDouble() ?? 1.5;

    if (content.isEmpty) {
      return [];
    }

    List<String> pages = [];
    final textStyle = TextStyle(
      fontSize: fontSize,
      height: lineHeightMultiple,
    );

    // 使用TextPainter进行精确测量
    final textPainter = TextPainter(
      textDirection: TextDirection.ltr,
    );

    int startPos = 0;
    while (startPos < content.length) {
      // 使用二分查找找到最佳分页点
      int endPos = _findBestPageBreak(content, startPos, content.length, pageWidth, pageHeight, textStyle, textPainter);

      // 防止无限循环
      if (endPos <= startPos) {
        endPos = startPos + 1;
      }

      // 优化分页点，尽量在语义合适的位置分页
      endPos = _optimizePageBreak(content, startPos, endPos);

      pages.add(content.substring(startPos, endPos));
      startPos = endPos;
    }

    textPainter.dispose();
    return pages;
  }

  // 查找最佳分页点
  static int _findBestPageBreak(
    String content,
    int startPos,
    int maxPos,
    double pageWidth,
    double pageHeight,
    TextStyle textStyle,
    TextPainter textPainter,
  ) {
    int low = startPos;
    int high = maxPos;

    // 使用二分查找找到最合适的分页点
    while (low < high) {
      int mid = (low + high + 1) ~/ 2;
      String testText = content.substring(startPos, mid);

      textPainter.text = TextSpan(text: testText, style: textStyle);
      textPainter.layout(maxWidth: pageWidth);

      if (textPainter.height <= pageHeight) {
        low = mid;
      } else {
        high = mid - 1;
      }
    }

    return low;
  }

  // 优化分页点，尽量在句子结尾或段落结尾分页
  static int _optimizePageBreak(String content, int startPos, int breakPos) {
    // 如果已经在内容末尾，直接返回
    if (breakPos >= content.length) {
      return breakPos;
    }

    // 向前查找合适的断点（句子结尾或段落结尾）
    for (int i = breakPos; i > startPos; i--) {
      // 在句号、感叹号、问号后分页
      if (i > 0 && (content[i - 1] == '。' || content[i - 1] == '！' || content[i - 1] == '？' || content[i - 1] == '；')) {
        return i;
      }
      // 在换行符后分页
      if (i > 0 && content[i - 1] == '\n') {
        // 检查是否是段落结尾（连续两个换行符）
        if (i < content.length && content[i] == '\n') {
          return i + 1;
        }
        return i;
      }
    }

    // 没有找到更好的断点，返回计算出的位置
    return breakPos;
  }

  static bool _isCJKPunctuation(String char) {
    final code = char.codeUnitAt(0);
    return (code >= 0x3000 && code <= 0x303F) || (code >= 0xFF00 && code <= 0xFFEF);
  }
}

// ... existing code ...
class contentPainter extends CustomPainter {
  final List<String> pages;
  final double fontSizevalue;

  contentPainter({required this.pages, required this.fontSizevalue});

  @override
  void paint(Canvas canvas, Size size) {
    final textPainter = TextPainter(
      textDirection: TextDirection.ltr,
      maxLines: null,
    );

    for (final page in pages) {
      textPainter.text = TextSpan(
        text: page,
        style: TextStyle(
          fontSize: fontSizevalue,
          color: Colors.black,
          height: 1.5, // 设置行高倍数
        ),
      );
      textPainter.layout(maxWidth: size.width);

      // 绘制文本，让它尽可能填满可用空间
      textPainter.paint(canvas, Offset(0, 0));
      break; // 每个CustomPaint只绘制一页
    }

    textPainter.dispose();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
// ... existing code ...
